package com.hopedove.net;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

/***
 *  处理与后端的请求
 */
public class WebServiceUtil {

    /***
     *  发请求给服务端
     * @param method 方法名
     * @param param 参数
     * @return 响应
     */
    public static String request(final String method, String param) {
        final String url = Settings.getUrl();
        final int timeout = Settings.TIMEOUT;
        final String nameSpace = Settings.NAME_SPACE;
        SoapObject request = new SoapObject(nameSpace, method);
        if (param != null) {
            request.addProperty("arg0", param);
        }

        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = false;
        envelope.setOutputSoapObject(request);

        final HttpTransportSE ht = new HttpTransportSE(url, timeout);
        ht.debug = true;
        String result = "";
        try {
            ht.call("\"" + nameSpace + method + "\"", envelope);
            if (envelope.getResponse() != null) {
                result = envelope.getResponse().toString();
            } else {
                result = error("response is null");
            }
        } catch (IOException | XmlPullParserException e) {
            result = error(e.toString());
        }
        return result;
    }


    private static String error(final String info) {
        return "[{\"OPT_FLAG\":1,\"MSG_INFO\":\"" + info + "\"}]";
    }

}
